package com.wonders.bigdata.nio;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Description: 利用文件通道和buffer将文字写入文件<br>
 *
 * @author: XB
 * @date: 2021/5/6 9:16
 */
public class NIOFilechannel01 {
    public static void main(String[] args) throws Exception {
        String str = "hello，五月";
        File file = new File("/file/netty");
        if(!file.exists()) {
            file.mkdirs();
        }
        // 创建一个输出流->channel
        FileOutputStream fileOutputStream = new FileOutputStream("/file/netty/file01.txt");
        // 通过fileOutputStream获取对应frfilechannel
        FileChannel fileChannel = fileOutputStream.getChannel();
        // 创建一个缓冲区ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 将str写入缓冲区
        byteBuffer.put(str.getBytes());
        // 对byteBuffer进行反转flip
        byteBuffer.flip();
        // 将byteBuffer数据写入到fileChannl
        fileChannel.write(byteBuffer);
        fileChannel.close();
        fileOutputStream.close();
    }
}
